﻿// Spun AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using Microsoft.Win32;

namespace Spun.Communications
{
    [RunInstaller(true)]
    public partial class SpunInstaller : Installer
    {
        private const string SubKeyName = "Spun";

        public SpunInstaller()
        {
            InitializeComponent();
        }

        protected override void OnAfterInstall(IDictionary savedState)
        {
            using (var Key = OpenAssemblyFoldersKey())
            using (var SubKey = OpenSubKey(Key) ?? CreateSubKey(Key))
                if (SubKey != null) SubKey.SetValue(null, @"C:\Program Files\Spun\Spun\");

            base.OnAfterInstall(savedState);
        }

        protected override void OnAfterRollback(IDictionary savedState)
        {
            RemoveRegKey();
            base.OnAfterRollback(savedState);
        }

        protected override void OnAfterUninstall(IDictionary savedState)
        {
            RemoveRegKey();
            base.OnAfterUninstall(savedState);
        }

        private RegistryKey CreateSubKey(RegistryKey Key)
        {
            try
            {
                return Key.CreateSubKey(SubKeyName);
            }
            catch
            {
                return null;
            }
        }

        private RegistryKey OpenSubKey(RegistryKey Key)
        {
            try
            {
                return Key.OpenSubKey(SubKeyName);
            }
            catch
            {
                return null;
            }
        }

        private static void RemoveRegKey()
        {
            try
            {
                using (var Key = OpenAssemblyFoldersKey())
                    Key.DeleteSubKey(SubKeyName);
            }
            catch { }
        }

        private static RegistryKey OpenAssemblyFoldersKey()
        {
            return Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework\AssemblyFolders", true);
        }
    }
}
